$(document).ready(function() {
	var accessToken = localStorage.getItem('access-token');

	if (accessToken === null) {
		$('#not-logged-in-form').show();
		$('#logged-in-form').hide();
		$('#login-message').hide();
		// TODO ratings hidden maken als niet ingelogd
	} else {
		$('#not-logged-in-form').hide();
		$('#logged-in-form').show();
		var username = localStorage.getItem('username');
		$('#logged-in-as').text("Logged in as: " + username);
		$('#welcome-text').text("Welcome " + username + "!");
		$('#login-message').show();
	}
});

var logout = function() {
	if (localStorage.getItem('access-token') !== null) {
		localStorage.removeItem('access-token');
		localStorage.removeItem('username');
		$('#login-form').show();
		$('#logged-in-div').hide();
		$('#my-ratings').hide();
		location.reload();
	}
};

$('#submit-login').click(function() {
	var username = $('#username-box').val();
	var password = $('#password-box').val();

	if (username === '' || password === '') {
		alert('Please fill in both fields!');
	} else {
		getToken(username, password);
	}
});

$('#logout-button').click(logout);

var getToken = function(username, password) {
	$.ajax({
		type : 'POST',
		url : 'api/login',
		beforeSend : function(request) {
			request.setRequestHeader("nickname", username);
			request.setRequestHeader("password", password);
		}
	}).fail(function(jgXHR, textStatus) {
		alert(jgXHR.status + ': ' + textStatus);
	}).success(function(data, textStatus, request) {
		loginSuccess(request.getResponseHeader('access-token'), username);
	});
};

var loginSuccess = function(accessToken, username) {
	localStorage.setItem('access-token', accessToken);
	localStorage.setItem('username', username);
	location.reload();
};